package com.xscha.tableforge.controller;

import com.xscha.soyue.common.core.domain.R;
import com.xscha.tableforge.model.vo.MetaVo;
import com.xscha.tableforge.model.vo.RouterVo;
import com.xscha.tableforge.model.vo.NodeMetaVo;
import com.xscha.tableforge.service.NodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/menu")
public class MenuController {
    
    @Autowired
    private NodeService nodeService;
    
    @GetMapping("/getRouters")
    public R<List<RouterVo>> getRouters() {
        List<RouterVo> routers = new ArrayList<>();
        
        // 创建系统管理路由
        RouterVo systemRouter = new RouterVo();
        systemRouter.setName("System1");
        systemRouter.setPath("/system");
        systemRouter.setHidden(false);
        systemRouter.setRedirect("noRedirect");
        systemRouter.setComponent("Layout");
        systemRouter.setAlwaysShow(true);
        
        // 设置系统管理元数据
        MetaVo systemMeta = new MetaVo();
        systemMeta.setTitle("系统管理");
        systemMeta.setIcon("eos-icons:system-group");
        systemMeta.setNoCache(false);
        systemMeta.setLink(null);
        systemRouter.setMeta(systemMeta);
        
        // 创建系统管理子路由
        List<RouterVo> systemChildren = new ArrayList<>();
        
        // 用户管理
        systemChildren.add(createChildRouter("User100", "user", "system/user/index", 
                "用户管理", "ph:user-duotone", false, null));
        
        // 角色管理
        systemChildren.add(createChildRouter("Role101", "role", "system/role/index", 
                "角色管理", "eos-icons:role-binding-outlined", false, null));
        
        // 菜单管理
        systemChildren.add(createChildRouter("Menu102", "menu", "system/menu/index", 
                "菜单管理", "ic:sharp-menu", false, null));
        
        // 部门管理
        systemChildren.add(createChildRouter("Dept103", "dept", "system/dept/index", 
                "部门管理", "mingcute:department-line", false, null));
        
        // 岗位管理
        systemChildren.add(createChildRouter("Post104", "post", "system/post/index", 
                "岗位管理", "icon-park-outline:appointment", false, null));
        
        // 字典管理
        systemChildren.add(createChildRouter("Dict105", "dict", "system/dict/index", 
                "字典管理", "fluent-mdl2:dictionary", false, null));
        
        // 参数设置
        systemChildren.add(createChildRouter("Config106", "config", "system/config/index", 
                "参数设置", "icon-park-twotone:setting-two", false, null));
        
        // 通知公告
        systemChildren.add(createChildRouter("Notice107", "notice", "system/notice/index", 
                "通知公告", "fe:notice-push", false, null));
        
        // 设置子路由
        systemRouter.setChildren(systemChildren);
        
        // 添加到路由列表
        routers.add(systemRouter);
        
        return R.ok(routers);
    }
    
    @GetMapping("/getAppRouters")
    public R<List<RouterVo>> getAppRouters(@RequestParam String appId) {
        // 获取应用下所有节点
        List<NodeMetaVo> nodes = nodeService.getAppNodes(appId);
        
        // 构建路由树
        List<RouterVo> routers = buildRouterTree(nodes);
        
        return R.ok(routers);
    }
    
    /**
     * 构建路由树
     */
    private List<RouterVo> buildRouterTree(List<NodeMetaVo> nodes) {
        List<RouterVo> routers = new ArrayList<>();
        
        // 按父节点ID分组
        Map<String, List<NodeMetaVo>> nodeMap = nodes.stream()
                .collect(Collectors.groupingBy(node -> 
                    node.getParentId() == null ? "" : node.getParentId()));
        
        // 从根节点开始构建
        List<NodeMetaVo> rootNodes = nodeMap.getOrDefault("", new ArrayList<>());
        for (NodeMetaVo rootNode : rootNodes) {
            RouterVo router = convertNodeToRouter(rootNode);
            buildChildrenRouters(router, nodeMap, nodes);
            routers.add(router);
        }
        
        return routers;
    }
    
    /**
     * 递归构建子路由
     */
    private void buildChildrenRouters(RouterVo parent, Map<String, List<NodeMetaVo>> nodeMap, List<NodeMetaVo> allNodes) {
        // 获取直接子节点
        List<NodeMetaVo> children = nodeMap.getOrDefault(parent.getName(), new ArrayList<>());
        
        if (!children.isEmpty()) {
            List<RouterVo> childRouters = new ArrayList<>();
            
            // 先处理分组
            Map<String, List<NodeMetaVo>> groupedNodes = children.stream()
                    .collect(Collectors.groupingBy(node -> 
                        node.getGroupId() == null ? "" : node.getGroupId()));
            
            // 处理未分组的节点
            List<NodeMetaVo> ungroupedNodes = groupedNodes.getOrDefault("", new ArrayList<>());
            for (NodeMetaVo node : ungroupedNodes) {
                RouterVo childRouter = convertNodeToRouter(node);
                buildChildrenRouters(childRouter, nodeMap, allNodes);
                childRouters.add(childRouter);
            }
            
            // 处理分组节点
            groupedNodes.forEach((groupId, groupNodes) -> {
                if (!groupId.isEmpty()) {
                    // 找到分组节点
                    NodeMetaVo groupNode = allNodes.stream()
                            .filter(n -> n.getNodeId().equals(groupId))
                            .findFirst()
                            .orElse(null);
                    
                    if (groupNode != null) {
                        RouterVo groupRouter = convertNodeToRouter(groupNode);
                        List<RouterVo> groupChildren = new ArrayList<>();
                        
                        // 添加分组下的子节点
                        for (NodeMetaVo node : groupNodes) {
                            RouterVo nodeRouter = convertNodeToRouter(node);
                            buildChildrenRouters(nodeRouter, nodeMap, allNodes);
                            groupChildren.add(nodeRouter);
                        }
                        
                        groupRouter.setChildren(groupChildren);
                        childRouters.add(groupRouter);
                    }
                }
            });
            
            parent.setChildren(childRouters);
        }
    }
    
    /**
     * 将节点转换为路由
     */
    private RouterVo convertNodeToRouter(NodeMetaVo node) {
        RouterVo router = new RouterVo();
        router.setName(node.getNodeId());
        router.setPath(node.getPath());
        router.setHidden(!node.getIsVisible());
        router.setRedirect(node.getRedirect());
        router.setComponent(node.getComponent());
        router.setAlwaysShow(node.getAlwaysShow());
        
        // 如果没有指定组件，根据节点类型设置默认组件
        if (router.getComponent() == null) {
            switch (node.getNodeType()) {
                case "0": // Root
                case "1": // Folder
                case "6": // Group
                    router.setComponent("Layout");
                    router.setAlwaysShow(true);
                    break;
                case "2": // Datasheet
                    router.setComponent("views/datasheet/index");
                    break;
                case "3": // Form
                    router.setComponent("views/form/index");
                    break;
                case "4": // Dashboard
                    router.setComponent("views/dashboard/index");
                    break;
                case "5": // iFrame
                    router.setComponent("views/iframe/index");
                    break;
                default:
                    router.setComponent("Layout");
            }
        }
        
        // 设置Meta信息
        MetaVo meta = new MetaVo();
        meta.setTitle(node.getNodeName());
        meta.setIcon(node.getIcon());
        meta.setNoCache(false);
        
        // 如果是iFrame，设置链接
        if ("5".equals(node.getNodeType()) && node.getExtra() != null) {
            meta.setLink(node.getExtra());
        }
        
        router.setMeta(meta);
        return router;
    }
    
    /**
     * 创建子路由
     */
    private RouterVo createChildRouter(String name, String path, String component, 
                                      String title, String icon, boolean noCache, String link) {
        RouterVo router = new RouterVo();
        router.setName(name);
        router.setPath(path);
        router.setHidden(false);
        router.setComponent(component);
        
        MetaVo meta = new MetaVo();
        meta.setTitle(title);
        meta.setIcon(icon);
        meta.setNoCache(noCache);
        meta.setLink(link);
        router.setMeta(meta);
        
        return router;
    }
}
